import router from "@/router";
import store from "@/store";
import Nprogress from 'nprogress'
import {getToken, handleRouter} from "@/utils";
import asyncRoutes from "@/router/asyncRoutes";
// 白名单路由
const whiteList = ['/login']

// 添加动态路由（优化版）
const addDynamicRoutes = () => {
    // 静态路由
    const userMenu = handleRouter(store.state.userStore.menuData);
    // 过滤掉返回菜单中不存在的
    const filterMenu = asyncRoutes.map(menu => {
        return {
            ...menu,
            children: menu.children.filter(childRoute => userMenu.some(item => item === childRoute.path))
        }
    })
    filterMenu.forEach(route => {
        router.addRoute(route);
    });
    // 通配404页面需要在最后添加
    router.addRoute({
        path: "/:pathMatch(.*)*",
        name: "NotFound",
        component: () => import("@/views/NotFound/NotFound.vue"),
        meta: {
            public: true,
            title: "404"
        }
    })
};

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
    Nprogress.start();
    const {token} = getToken();
    if (token) {
        if (to.path === '/login') {
            // 修改为直接跳转，不使用replace
            next('/home');
            return;
        }
        try {
            const userData = store.state.userStore.userData;
            if (!userData || Object.keys(userData).length === 0) {
                await store.dispatch('userStore/getUserInfo');
                await addDynamicRoutes();
                next({path: to.path, replace: true});
                return
            }
            next()
        } catch (error) {
            console.error('获取用户信息失败:', error);
            next(`/login?redirect=${to.path}`);
        }
    } else {
        if (whiteList.includes(to.path)) {
            next();
        } else {
            next(`/login?redirect=${to.path}`);
        }
    }
    if (to.meta.title) {
        document.title = `${to.meta.title}`;
    }
});

// 路由后置守卫
router.afterEach(() => {
    Nprogress.done();
});
